/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import database.DBConnectionFactory;

/**
 * This class represents a help topic
 * 
 * 
 */
public class HelpTopic implements BotObject {
   /**
    * Removes the specified help topic. If it's a master topic, the connected sub topics are removed as well
    * 
    * @param args
    *           The name of the topic to remove
    * @return true if the topic is successfully deleted
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 1)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM help WHERE topic = ?");
		 ps.setString(1, args[0]);
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
		 removeSubTopic(args[0]);
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns the specified help topic
    * 
    * @param topic
    * @return a HelpTopic object. Returns null if no topic is found
    */
   public static HelpTopic getHelpTopic(final String topic) {
	  if (topic == null)
		 return null;
	  HelpTopic out = null;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM help WHERE topic = ?");
		 ps.setString(1, topic);
		 rs = ps.executeQuery();

		 while (rs.next()) {
			out = new HelpTopic(rs.getString("topic"), rs.getString("helptext"), rs.getString("mastertopic"));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of all help topics
    * 
    * @return a List of HelpTopic objects
    */
   public static List<HelpTopic> getHelpTopics() {
	  List<HelpTopic> out = new LinkedList<HelpTopic>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM help");
		 rs = ps.executeQuery();

		 while (rs.next()) {
			out.add(new HelpTopic(rs.getString("topic"), rs.getString("helptext"), rs.getString("mastertopic")));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Used to remove sub topics
    * 
    * @param master
    *           The name of the master topic
    */
   private static void removeSubTopic(final String master) {
	  if (master == null)
		 return;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM help WHERE mastertopic = ?");
		 ps.setString(1, master);
		 rs = ps.executeQuery();

		 while (rs.next()) {
			removeSubTopic(rs.getString("topic"));
		 }

		 try {
			ps.close();
		 } catch (final Exception e) {
		 }

		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("DELETE FROM help WHERE mastertopic = ?");
		 ps.setString(1, master);
		 ps.executeUpdate();
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
   }

   private String topic = "";

   private String help = "";

   private String masterTopic = "";

   public HelpTopic(final String topic, final String help, final String masterTopic) {
	  this.topic = topic;
	  this.help = help;
	  this.masterTopic = masterTopic;
   }

   public String getHelp() {
	  return help;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (StringTools.isNullOrEmpty(getTopic()) || help == null || masterTopic == null)
		 return out;
	  String helptext = getHelp();
	  helptext = helptext.replaceAll("BLACK", Colors.BLACK);
	  helptext = helptext.replaceAll("BLUE", Colors.BLUE);
	  helptext = helptext.replaceAll("BOLD", Colors.BOLD);
	  helptext = helptext.replaceAll("BROWN", Colors.BROWN);
	  helptext = helptext.replaceAll("CYAN", Colors.CYAN);
	  helptext = helptext.replaceAll("DARKBLUE", Colors.DARK_BLUE);
	  helptext = helptext.replaceAll("DARKGREY", Colors.DARK_GRAY);
	  helptext = helptext.replaceAll("DARKGREEN", Colors.DARK_GREEN);
	  helptext = helptext.replaceAll("GREEN", Colors.GREEN);
	  helptext = helptext.replaceAll("LIGHTGREY", Colors.LIGHT_GRAY);
	  helptext = helptext.replaceAll("MAGENTA", Colors.MAGENTA);
	  helptext = helptext.replaceAll("NORMAL", Colors.NORMAL);
	  helptext = helptext.replaceAll("OLIVE", Colors.OLIVE);
	  helptext = helptext.replaceAll("PURPLE", Colors.PURPLE);
	  helptext = helptext.replaceAll("RED", Colors.RED);
	  helptext = helptext.replaceAll("REVERSE", Colors.REVERSE);
	  helptext = helptext.replaceAll("TEAL", Colors.TEAL);
	  helptext = helptext.replaceAll("UNDERLINE", Colors.UNDERLINE);
	  helptext = helptext.replaceAll("WHITE", Colors.WHITE);
	  helptext = helptext.replaceAll("YELLOW", Colors.YELLOW);
	  for (String s : helptext.split("\n")) {
		 if (!"".equals(s)) {
			out.add(s);
		 }
	  }
	  String output = topic + " has the following sub topics: ";
	  for (String s : getSubTopics()) {
		 if (output.length() > 350) {
			out.add(output.substring(0, output.length() - 4));
			output = "";
		 }
		 output += s + " <> ";
	  }
	  if (output.length() > 4 && !output.equals(topic + " has the following sub topics: ")) {
		 out.add(output.substring(0, output.length() - 4));
	  }
	  return out;
   }

   public String getMasterTopic() {
	  return masterTopic;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getTopic()) || help == null || masterTopic == null)
		 return out;
	  out.put("Topic", getTopic());
	  out.put("Help", getHelp());
	  return out;
   }

   /**
    * Returns the sub topics belonging to the topic in this instance
    * 
    * @return List of Strings which are the names of sub topics
    */
   private List<String> getSubTopics() {
	  List<String> out = new LinkedList<String>();
	  if (StringTools.isNullOrEmpty(getTopic()) || help == null || masterTopic == null)
		 return out;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM help WHERE mastertopic = ?");
		 ps.setString(1, getTopic());
		 rs = ps.executeQuery();
		 while (rs.next()) {
			out.add(rs.getString("topic"));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   public String getTopic() {
	  return topic;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getTopic()) || help == null || masterTopic == null)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("INSERT INTO help VALUES(?,?,?)");
		 ps.setString(1, getTopic());
		 ps.setString(2, getHelp());
		 ps.setString(3, getMasterTopic());
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }
}
